package com.kehutong.session.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.kehutong.session.dao.SessionDao;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.webservice.WebService;
import org.coraframework.orm.Pool;
import org.coraframework.orm.annotation.Column;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.execute.Condition;
import org.coraframework.orm.util.Enums;
import org.coraframework.util.Objects;

import com.kehutong.common.enums.UserType;
import com.kehutong.common.errcode.Result;
import com.kehutong.session.entity.Session;

@WebService("/kht-bin/session/service")
public class SessionService {

	private static Logger logger = LoggerFactory.getLogger(SessionService.class);

	@Inject
	private JdbcSession jdbcSession;
	@Inject
	private SessionDao sessionDao;

	@ReqMapping("/login")
	public Object onLogin(JSONObject jsonObject) {
		logger.debug("=======onLogin====={}", jsonObject);
		String sessionId=jsonObject.getString("sessionId");
		Session session = jdbcSession.findById(Session.class, sessionId);
		if (session==null || session.isDeleted()) {
			session = Pool.newInstance(Session.class,sessionId);
			setProperties(session, jsonObject);
			jdbcSession.insert(session);
		} else {
			setProperties(session, jsonObject);
			jdbcSession.updateById(session);
		}
		return Result.success();
	}
	
	@ReqMapping("/change")
	public Object change(String id, String permissions) {
		logger.debug("=======session change=====id: {}, permission:{}", id, permissions);
		Session session = jdbcSession.findById(Session.class, id);
		if (Objects.nonNull(session)){
			session.setPermissions(permissions);
			jdbcSession.updateById(session);
		}
		return Result.success();
	}
	@ReqMapping("/changeExt")
	public Object changeExt(String id, String ext) {
		logger.debug("=======session change=====id: {}, ext:{}", id, ext);
		Session session = jdbcSession.findById(Session.class, id);
		if (Objects.nonNull(session)){
			session.setExtContent(ext);
			jdbcSession.updateById(session);
		}
		return Result.success();
	}
	@ReqMapping("/logout")
	public Object onLogout(String sessionId) {
		Session session = jdbcSession.findById(Session.class, sessionId);
		if (Objects.nonNull(session)) {
			session.setDeleted(true);
			jdbcSession.updateById(session);
		}
		return Result.success();
	}

	@ReqMapping("/batch/logout")
	public Object batchLogout(String companyNo) {
		Condition query = Condition.create(false).eq("companyNo", companyNo);
		sessionDao.deleteSession(query);
		return Result.success();
	}

	@ReqMapping("/get")
	public Object get(String sessionId) {
		logger.debug("get======={}", sessionId);
		Session session = jdbcSession.findById(Session.class, sessionId);
		if (Objects.isNull(session) || session.isDeleted()) {
			return Result.error(1002, "session is not exist.");
		}

//		if (session.isExpired()) {
//			session.setDeleted(true);
//			jdbcSession.updateById(session);
//			return Result.error(1003, "session is expired.");
//		}

		// todo 刷新过期时间
		return toJSON(session);
	}

	private void setProperties(Session session, JSONObject jsonObject) {
		session.setCompanyNo(jsonObject.getString("companyNo"));
		session.setCompanyName(jsonObject.getString("companyName"));
		session.setDepartment(jsonObject.getString("departments"));
		session.setCorpid(jsonObject.getString("corpid"));
		session.setSuiteId(jsonObject.getString("suiteId"));
		session.setUuid(jsonObject.getString("uuid"));
		session.setUserId(jsonObject.getString("userId"));
		session.setUsername(jsonObject.getString("username"));
		session.setMobile(jsonObject.getString("mobile"));
		session.setHeadUrl(jsonObject.getString("headUrl"));
		session.setRoles(jsonObject.getString("roles"));
		session.setPermissions(jsonObject.getString("permissions"));
		session.setDeleted(false);
		session.setUserType(Enums.getEnum(UserType.class, jsonObject.getString("type")));
		session.setUserCreateTime(jsonObject.getLongValue("userCreateTime"));
		session.setVersion(jsonObject.getString("version"));
		session.setExtContent(jsonObject.getString("extContent"));

		session.setSettingState(jsonObject.getBooleanValue("settingState"));
		session.setNewsletterState(jsonObject.getBooleanValue("newsletterState"));
		session.setFrontPageState(jsonObject.getBooleanValue("frontPageState"));
		session.setBusinessState(jsonObject.getBooleanValue("businessState"));
		session.setRemindTime(jsonObject.getLong("remindTime"));

	}

	private JSONObject toJSON(Session session) {
		JSONObject jsonObject = new JSONObject(8);

		jsonObject.put("id", session.getId());
		jsonObject.put("companyNo", session.getCompanyNo());
		jsonObject.put("companyName", session.getCompanyName());
		jsonObject.put("departments", session.getDepartment());
		jsonObject.put("corpid", session.getCorpid());
		jsonObject.put("suiteId", session.getSuiteId());
		jsonObject.put("uuid", session.getUuid());
		jsonObject.put("userId", session.getUserId());
		jsonObject.put("username", session.getUsername());
		jsonObject.put("mobile", session.getMobile());
		jsonObject.put("headUrl", session.getHeadUrl());
		jsonObject.put("roles", String.join(",", session.getRoles()));
		jsonObject.put("permissions", String.join(",", session.getPermissions()));
		jsonObject.put("type", session.getUserType().getId());
		jsonObject.put("timestamp", session.getCreateTime().getTime());
		jsonObject.put("userCreateTime", session.getUserCreateTime());
		jsonObject.put("version",session.getVersion());
		jsonObject.put("extContent",session.getExtContent());

        jsonObject.put("remindTime", session.getRemindTime());
		jsonObject.put("settingState", session.isSettingState());
		jsonObject.put("newsletterState", session.isNewsletterState());
		jsonObject.put("businessState",session.isBusinessState());
		jsonObject.put("frontPageState",session.isFrontPageState());

		return jsonObject;
	}


	public static List<String> fromJSONAray(String str) {
		if (Objects.isEmpty(str)) {
			return Collections.emptyList();
		}

		String[] strs = str.split(",");
		List<String> set = new ArrayList<>(strs.length);
		for (int i = 0, j = strs.length; i < j; i ++) {
			set.add(strs[i]);
		}

		return set;
	}
}